<template>
    <div>
        <!--搜索区域-->
        <div class="search">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.state" placeholder="请选择用户状态">
                        <el-option label="正常" :value="1"></el-option>
                        <el-option label="禁用" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchSubmit">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-refresh" @click="clearSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--头部工具栏-->
        <div class="header-btn">
            <el-button type="primary" size="small" @click="showAddUserForm">添加</el-button>
            <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
        </div>
        <!--数据展示区-->
        <div class="data-table">
            <el-table
                    :data="tableData"
                    @selection-change="handleSelectionChange"
                    style="width: 100%">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>

                <el-table-column label="用户名">
                    <template slot-scope="scope">
                        <span>{{ scope.row.username }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="昵称">
                    <template slot-scope="scope">
                        <span>{{ scope.row.nickName }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="性别">
                    <template slot-scope="scope">
                        <span v-if="scope.row.sex==1">男</span>
                        <span v-if="scope.row.sex==0">女</span>
                    </template>
                </el-table-column>

                <el-table-column label="地址" width="120px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.city }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="部门">
                    <template slot-scope="scope">
                        <span>{{ scope.row.deptName }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="联系方式" width="150px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.tel }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="角色" width="180px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.roleNames.join("&nbsp;&nbsp;") }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="用户状态">
                    <template slot-scope="scope">
                        <el-switch
                                @change="changeUserState(scope.row)"
                                v-model="scope.row.state"
                                :inactive-value="0"
                                :active-value="1"
                                active-color="#13ce66"
                                inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间">
                    <template slot-scope="scope">
                        <span>{{ scope.row.createTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150px">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--分页导航区域-->
        <div class="nav-page">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="searchForm.limit"
                    :current-page="searchForm.currentPage"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--添加 编辑用户信息弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="addUserFormVisible" width="50%" @close="clearInfo">
            <el-form :model="userForm" ref="userInfo" :rules="userRules" label-width="90px" size="medium">
                <el-input v-model="userForm.id" autocomplete="off" v-show="false"></el-input>
                <el-form-item label="用户名" prop="username" v-show="dialogTitle=='添加用户'">
                    <el-input v-model="userForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="userForm.nickName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="userForm.sex" placeholder="请选择性别" style="width: 100%">
                        <el-option label="男" :value="1"></el-option>
                        <el-option label="女" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="地址" prop="city">
                    <el-input v-model="userForm.city" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="tel">
                    <el-input v-model="userForm.tel" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <el-select v-model="userForm.deptId" placeholder="请选择部门" style="width: 100%">
                        <el-option v-for="(dept,index) in deptList" :label="dept.deptName"  :key="index":value="dept.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色" prop="roleIds" multiple>
                    <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                        <el-option v-for="(role,index) in roleList" :key="index" :label="role.roleCh" :value="role.roleId"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addUserInfo">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {
        addOrUpdateUser,
        batchDeleteUserApi,
        getDeptListApi,
        getRoleListApi, getUserInfoByIdApi,
        getUserPageApi,
        updateUserStateApi
    } from '@/request/api'

    export default {
        name: "UserView",
        data() {
            return {
                addUserFormVisible: false,
                deptList:[],
                roleList:[],
                dialogTitle: "添加用户",
                /*数据的总条数*/
                total: 130,
                /*搜索数据*/
                searchForm: {
                    limit: 5,
                    currentPage: 1
                },
                userForm: {},
                userRules: {
                    username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                    nickName: [{required: true, message: '请输入昵称', trigger: 'blur'}],
                    roleIds: [{required: true, message: '请选择角色', trigger: 'blur'}],
                    deptId: [{required: true, message: '请输入用户名', trigger: 'blur'}]
                },
                /*表格数据*/
                tableData: [],
                /*复选框数据*/
                multipleSelection: []
            }
        },
        methods: {
            //改变用户的状态
            changeUserState(row) {
                updateUserStateApi({id: row.id, state: row.state}).then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: "success",
                            message: response.msg,
                        })
                        this.list();
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            // 重置搜索数据对象
            clearSearch() {
                this.searchForm = {
                    limit: this.searchForm.limit,
                    currentPage: this.searchForm.currentPage
                }
            },
            /*搜索回调*/
            searchSubmit() {
                this.searchForm.currentPage = 1
                this.searchForm.limit = 5
                this.list()
            },
            // 显示添加用户信息弹窗
            showAddUserForm(){
                this.addUserFormVisible=true
                this.dialogTitle='添加用户'
            },
            /*编辑用户信息回调函数*/
            handleEdit(index, row) {
                this.addUserFormVisible=true
                this.dialogTitle='编辑用户'
                console.log(index, row);
                console.log()
                // 获取用户的id  发送请求 获取用户详细信息
                getUserInfoByIdApi(row.id).then(response=>{
                    this.userForm = response.data
                })
            },
            // 渲染弹窗下拉选
            async  renderSelect(){
                 // 获取角色列表   response  {code msg data}
                let roleData  =  await getRoleListApi()
                this.roleList = roleData.data  // [{role},{}]
                 //获取部门列表
                let deptData =   await getDeptListApi()
                this.deptList = deptData.data   // [{dept},{}]
            },
            /*删除用户信息回调函数*/
            handleDelete(index, row) {
                this.multipleSelection = [row.id]
                batchDeleteUserApi(this.multipleSelection).then(response => {
                    if (response.code == 200) {
                        this.$message.success(response.msg);
                        this.list();
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            /*复选框回调函数*/
            handleSelectionChange(val) {
                this.multipleSelection = val.map(row => row.id)
            },

            // 批量删除用户信息
            batchDelete() {
                // 判定用户是否选择 删除的数据
                if (!this.multipleSelection.length) {
                    this.$message.warning("请至少选择一条数据")
                    return
                }
                batchDeleteUserApi(this.multipleSelection).then(response => {
                    if (response.code == 200) {
                        this.$message.success(response.msg);
                        this.list();
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            /*改变每页显示条数时回调*/
            handleSizeChange(val) {
                this.searchForm.limit = val
                this.list()
                console.log(this.searchForm)
            },
            /*改变页码时回调*/
            handleCurrentChange(val) {
                this.searchForm.currentPage = val
                this.list();
                console.log(this.searchForm)
            },
            list() {
                // 发送异步请求  获取用户信息列表
                getUserPageApi(this.searchForm).then(response => {
                    if (response.code == 200) {
                        this.tableData = response.data.pageData
                        this.total = response.data.total
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            addUserInfo() {
                this.$refs.userInfo.validate(valid => {
                    if (!valid) {
                        this.$message.error("请填写必要数据")
                        return
                    }
                    // 发送异步请求 添加用户信息
                    console.log(this.userForm)
                    addOrUpdateUser(this.userForm).then(response=>{
                        if(response.code==200){
                            this.$message.success(response.msg)
                            this.addUserFormVisible=false
                            this.userForm = {}
                            // 重新加载数据
                            this.list()
                            return
                        }
                        this.$message.warning(response.msg)
                    }).catch(error=>{
                        this.$message.error("请求失败")
                    })
                })
            },
            clearInfo() {
                this.userForm = {}
                this.$refs.userInfo.clearValidate()
            },
        },
        created() {
            this.renderSelect()
            this.list()
        }
    }
</script>

<style scoped>

    .search {
        padding: 10px;
        border-bottom: 1px solid #eee;
    }

    .header-btn, .nav-page {
        padding-top: 15px;
        padding-bottom: 10px;
    }

</style>
